
package com.tools.cleanmaster.functionpage;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Xfermode;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;

import com.tools.cleanmaster.utils.UiUtils;
import com.tools.cleanmaster.utils.Utils;

public class CoolDownView extends View {

    private static final int OUTER_CYCLE_STROKE_WIDTH = 3;

    public interface SnowAnimListener {
        void onStart();

        void onEnd();
    }

    private static final long TOTAL_SCAN_TIME = 1000;

    private float mCenterX;
    private float mCenterY;
    private float mTranlateWidth;
    private Paint mCirclePaint;
    private Paint mOuterPaint;

    private float mRadius;
    private Matrix mMatrix;
    private Bitmap mSnowBitmap;
    private int mSnowHalfBitmapHeight;

    private float mSnowBgHeight;
    private int mTotalWidth;
    private int mTotalHeight;
    private long mStartTime = -1;
    private Interpolator mInterpolator;
    private Xfermode mPorterDuffXfermode;

    private Paint mSnowPaint;
    private PaintFlagsDrawFilter mDrawFilter;
    private Bitmap mCircleBitmap;
    private Rect mCircleSrcRect;
    private Rect mCircleDestRect;
    private int mCircleHalfWidth;
    private int mCircleHalfHeight;
    private int mAdditionalRadius;
    private int[] mColorInt;
    private float[] mColorPostion;
    private SnowAnimListener snowAnimListener;
    // 控制开始时间的变量
    private boolean mIsStart = false;
    private boolean mIsFinished = false;
    private double mSinScaleX;
    private Context mContext;

    public CoolDownView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CoolDownView(Context context) {
        super(context);
        init(context);
    }

    public CoolDownView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }



    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTotalWidth = w;
        mTotalHeight = h;
        mCenterX = w / 2;
        mCenterY = h / 2;
        int circleWidth = mCircleBitmap.getWidth();
        int circleHeight = mCircleBitmap.getHeight();
        mCircleHalfWidth = circleWidth / 2;
        mCircleHalfHeight = circleHeight / 2;

        int snowBitmapWidth = mSnowBitmap.getWidth();
        int snowBitmapHeight = mSnowBitmap.getHeight();
        mSnowHalfBitmapHeight = snowBitmapHeight / 2;

        mRadius = circleWidth;

        mSnowBgHeight = (mCenterY - snowBitmapHeight) / 2;
        mTranlateWidth = (mTotalWidth - snowBitmapWidth) / 2;

        mCircleSrcRect = new Rect(0, 0, circleWidth, circleHeight);
        mCircleDestRect = new Rect((int) mCenterX - mCircleHalfWidth, (int) (mCenterY
                - mCircleHalfHeight),
                (int) mCenterX + mCircleHalfWidth,
                (int) (mCenterY + mCircleHalfHeight));

        // 1.圆心X坐标2.Y坐标3.半径 4.颜色数组 5.相对位置数组，可为null 6.渲染器平铺模式
        RadialGradient radialGradient = new RadialGradient(mCenterX, mCenterY, mCircleHalfWidth
                + mAdditionalRadius, mColorInt, mColorPostion, Shader.TileMode.CLAMP);
        mOuterPaint.setShader(radialGradient);

        mSinScaleX = 2 * Math.PI / TOTAL_SCAN_TIME;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 从canvas层面去除锯齿
        canvas.setDrawFilter(mDrawFilter);
        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);
        canvas.drawCircle(mCenterX, mCenterY, mCircleHalfWidth + mAdditionalRadius, mOuterPaint);
        canvas.drawCircle(mCenterX, mCenterY, mCircleHalfWidth, mCirclePaint);
        if (!mIsStart) {
            return;
        }

        long currentTime = System.currentTimeMillis();
        if (mStartTime == -1) {
            mStartTime = currentTime;
            if (snowAnimListener != null) {
                snowAnimListener.onStart();
            }
        }
        if (mIsFinished) {
            drawSnow(canvas, true);
            return;
        }
        long intervalTime = currentTime - mStartTime;
        if (intervalTime < TOTAL_SCAN_TIME) {
            float timeInterval = mInterpolator.getInterpolation((float) intervalTime
                    / TOTAL_SCAN_TIME);
            mSnowBgHeight = (int) ((mRadius - mSnowHalfBitmapHeight) * timeInterval) + mCenterY
                    - mRadius;

            double scaleX = Math.sin(mSinScaleX * intervalTime + Math.PI / 2);
            mMatrix.setTranslate(mTranlateWidth, mSnowBgHeight);
            mMatrix.postScale((float) scaleX, 1f, mCenterX, mCenterY);
            drawSnow(canvas, false);
            postInvalidate();
        } else {
            if (mSnowBgHeight > mCenterY) {
                mSnowBgHeight = mCenterY;
            }
            drawSnow(canvas, true);
            if (snowAnimListener != null) {
                snowAnimListener.onEnd();
            }
            mIsFinished = true;
        }
    }

    private void drawSnow(Canvas canvas, boolean isFinish) {
        if (isFinish) {
            canvas.drawBitmap(mSnowBitmap, mTranlateWidth, mSnowBgHeight, mSnowPaint);
        } else {
            /*
             * 将绘制操作保存到新的图层
             */
            int sc = canvas.saveLayer(0, 0, mTotalWidth, mTotalHeight, null, Canvas.ALL_SAVE_FLAG);
            canvas.drawBitmap(mSnowBitmap, mMatrix, mSnowPaint);
            // 设置图像的混合模式
            mSnowPaint.setXfermode(mPorterDuffXfermode);
            // 绘制遮罩圆
            canvas.drawBitmap(mCircleBitmap, mCircleSrcRect, mCircleDestRect, mSnowPaint);
            mSnowPaint.setXfermode(null);
            canvas.restoreToCount(sc);
        }
    }

    private void initPaint() {
        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(getResources().getColor(com.tools.cleanmaster.R.color.outer_circle_color));
        mCirclePaint.setDither(true);
        mCirclePaint.setStyle(Style.STROKE);
        mCirclePaint.setStrokeWidth(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
                getResources().getDisplayMetrics()));
        mCirclePaint.setStrokeWidth(UiUtils.dip2px(mContext, OUTER_CYCLE_STROKE_WIDTH));

        mOuterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mOuterPaint.setDither(true);

        mSnowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 防抖动
        mSnowPaint.setDither(true);
        // 开启图像过滤
        mSnowPaint.setFilterBitmap(true);
    }

    // 初始化混合模式
    private void initXfermode() {
        mPorterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
    }

    private void initBitmap() {
        mSnowBitmap = Utils.decodeSampledBitmapFromResource(getResources(),
                com.tools.cleanmaster.R.drawable.cpu_cool_down_snow,
                UiUtils.dip2px(getContext(), 210), UiUtils.dip2px(getContext(), 210));
        mCircleBitmap = ((BitmapDrawable) getResources().getDrawable(com.tools.cleanmaster.R.drawable.cpu_cool_down_circle_bg)).getBitmap();
    }

    private void init(Context context) {
        mContext = context;
        initPaint();
        initBitmap();
        initXfermode();
        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
                | Paint.FILTER_BITMAP_FLAG);
        mInterpolator = new LinearInterpolator();
        mColorInt = new int[]{
                getResources().getColor(com.tools.cleanmaster.R.color.inner_circle_color),
                getResources().getColor(com.tools.cleanmaster.R.color.inner_circle_color), Color.TRANSPARENT
        };
        mColorPostion = new float[]{
                0, 0.85f, 1
        };
        mAdditionalRadius = (int) getResources().getDimension(com.tools.cleanmaster.R.dimen.circle_fix_height);

        mMatrix = new Matrix();
    }

    public void startSnow(SnowAnimListener snowAnimListener) {
        this.snowAnimListener = snowAnimListener;
        mIsStart = true;
        mIsFinished = false;
        postInvalidate();
    }

    public void dismiss() {
        final ValueAnimator alphaAnimator = ValueAnimator.ofFloat(0, 1);
        alphaAnimator.setInterpolator(new LinearInterpolator());
        alphaAnimator.setDuration(200);
        alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                float animatorValue = (Float) animator.getAnimatedValue();
                CoolDownView.this.setScaleX(1 - animatorValue);
                CoolDownView.this.setScaleY(1 - animatorValue);
                CoolDownView.this.setAlpha(1 - animatorValue);
            }
        });
        alphaAnimator.start();
    }
}
